package vip.liux.backend.infrastructure.excel.handler;


import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import vip.liux.backend.infrastructure.excel.ExportContext;
import vip.liux.backend.infrastructure.excel.exception.ExcelException;

import java.io.OutputStream;
import java.util.List;
import java.util.Objects;

/**
 * @author JiaDu
 * @version 1.0.0
 * @since 2023/10/12
 */
public class SingleSheetWriteHandler extends AbstractSheetWriteHandler {

    /**
     * obj 是List 且list不为空同时list中的元素不是是List 才返回true
     *
     * @param obj 返回对象
     * @return boolean
     */
    @Override
    public boolean support(Object obj) {
        if (obj instanceof List<?> objList) {
            return !objList.isEmpty() && !(objList.get(0) instanceof List<?>);
        } else {
            throw new ExcelException("@ExportExcel 返回值必须为List类型");
        }
    }

    /**
     * 写入数据到Excel文件
     *
     * @param obj          导出数据，必须为List类型
     * @param outputStream 输出流，不能为空
     * @param exportContext 导出上下文配置，不能为空
     */
    @Override
    public void write(Object obj, OutputStream outputStream, ExportContext exportContext) {
        Assert.isInstanceOf(List.class, obj, "导出数据必须为List类型");
        Assert.notNull(outputStream, "输出流不能为空");
        Assert.notNull(exportContext, "导出上下文配置不能为空");

        List<?> dataList = (List<?>) obj;
        ExcelWriter excelWriter = getExcelWriter(outputStream, exportContext);

        Boolean useTemplate = StringUtils.isNotBlank(exportContext.getLocalTemplate())
                              || Objects.nonNull(exportContext.getRemoteTemplate());
        WriteSheet sheet;
        if (CollectionUtils.isEmpty(dataList)) {
            sheet = EasyExcelFactory.writerSheet(exportContext.getSheets().get(0).getSheetName()).build();
        } else {
            Class<?> dataClass = dataList.get(0).getClass();
            sheet = this.sheet(exportContext.getSheets().get(0), dataClass, useTemplate,
                    exportContext.getHeadGenerateClass());
        }

        // 填充 sheet
        if (exportContext.isFill()) {
            excelWriter.fill(dataList, sheet);
        } else {
            // 写入sheet
            excelWriter.write(dataList, sheet);
        }
        excelWriter.finish();
    }
}
